<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')"
			   :close-on-click-modal="false">
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px"
				 label-position="left">
			<el-form-item label="角色名称" prop="name">
				<el-input v-model="form.name" clearable></el-input>
			</el-form-item>
			<el-form-item label="&nbsp;&nbsp;备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注" prop="description">
			<el-input v-model="form.description" clearable type="textarea" rows="4" maxlength="50"
						  show-word-limit></el-input>
			</el-form-item>
			<el-form-item label="菜单权限" prop="permissionIds">
				<el-tree ref="menu" node-key="permissionId" :data="menu.list" :props="menu.props" style="width: 100%"
						 :default-checked-keys="menu.defaultCheckedKeys" @check="clickDeal" :default-expanded-keys="menu.treeData"
						 show-checkbox></el-tree>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>
export default {
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增角色',
				edit: '编辑角色',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
			// 表单数据
			form: {
				roleId: "",
				name: "",
				description: "",
				permissionIds: []
			},
			// 菜单结构数据
			menu: {
				list: [],
				treeData: [],
				defaultCheckedKeys: [],
				props: {
					value: 'permissionId',
					label: 'name',
					children: 'permissionList',
				}
			},
			// 验证规则
			rules: {
				name: [
					{required: true, message: '请输入角色名称'}
				],
				description: [
					{required: true, message: '请输入备注信息'}
				],
				permissionIds: [
					{required: true, message: '请选择角色所支持的权限'}
				]
			}
		}
	},
	mounted() {
		this.init();
	},
	methods: {

		/**
		 * 显示当前组件窗口
		 * @param mode
		 * @returns {default.methods}
		 */
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},

		/**
		 * 加载初始化数据
		 * @returns {Promise<void>}
		 */
		async init() {
			if (this.menu.list == undefined || this.menu.list.length == 0) {
				let data = await this.$API.system.role.getMenuList.get();
				data = data.data
				this.menu.list = data;
			}
		},

		/**
		 * 父组件提前设置当前子组件中的菜单tree列表（解决网络延迟显示慢的问题）
		 * @param data
		 * @returns {Promise<default.methods>}
		 */
		initMenu(data) {
			this.menu.list = data;
			this.getDefaultShowNodes(1, this.menu.list) //第一个参数，展开的数量,第二个数据
			return this;
		},

		/**
		 * 菜单tree树组件复选框 勾选事件
		 * @param currentObj
		 * @param treeStatus
		 */
		clickDeal(currentObj, treeStatus) {
			let ids = [];
			ids = ids.concat(treeStatus.checkedKeys).concat(treeStatus.halfCheckedKeys)
			this.form.permissionIds = ids;
		},

		getDefaultShowNodes(num, children) {
			--num
			if (num >= 0) {
				for (let i = 0; i < children.length; i++) {
					this.menu.treeData.push(children[i].permissionId)
					if (children[i].permissionList) {
						this.getDefaultShowNodes(num, children[i].permissionList)
					}
				}
			}
		},

		/**
		 * 表单提交方法
		 */
		submit() {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					let nodes = this.$refs.menu.getCheckedKeys().concat(this.$refs.menu.getHalfCheckedKeys());
					let params = {};
					Object.assign(params, this.form)
					params.permissionIds = nodes
					this.isSaveing = true;
					var res;
					if (this.mode == 'add') {
						res = await this.$API.system.role.add.post(params);
					} else {
						res = await this.$API.system.role.edit.put(params);
					}
					this.isSaveing = false;
					if (res.status == 200) {
						this.$emit('success')
						this.visible = false;
						this.$message.success("操作成功")
					}
				}
			})
		},

		/**
		 * 表单注入数据
		 * @param data
		 */
		setData(data) {
			this.form.roleId = data.roleId
			this.form.name = data.name
			this.form.description = data.description
			let menus = [];
			for (let t of data.permissions) {
				menus.push(t.permissionId)
			}
			this.form.permissionIds = menus;
			this.menu.defaultCheckedKeys = this.form.permissionIds;

			//可以和上面一样单个注入，也可以像下面一样直接合并进去
			//Object.assign(this.form, data)
		}
	}
}
</script>

<style>
</style>
